export let isAndroid = navigator.userAgent.indexOf('Android') > -1 || navigator.userAgent.indexOf('Adr') > -1;
export let isiOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);


function setupWebViewJavascriptBridge(callback) {
	if (isAndroid) {
		if (window.WebViewJavascriptBridge) {
			callback(WebViewJavascriptBridge)
		} else {
			document.addEventListener(
				'WebViewJavascriptBridgeReady',
				function () {
					callback(WebViewJavascriptBridge)
				},
				false
			);
		}
		sessionStorage.phoneType = 'android'
	}

	if (isiOS) {
		if (window.WebViewJavascriptBridge) {
			return callback(WebViewJavascriptBridge);
		}
		if (window.WVJBCallbacks) {
			return window.WVJBCallbacks.push(callback);
		}
		window.WVJBCallbacks = [callback];
		var WVJBIframe = document.createElement('iframe');
		WVJBIframe.style.display = 'none';
		WVJBIframe.src = 'https://__bridge_loaded__';
		document.documentElement.appendChild(WVJBIframe);
		setTimeout(function () {
			document.documentElement.removeChild(WVJBIframe)
		}, 0)
		sessionStorage.phoneType = 'ios'
	}
}

//注册回调函数，第一次连接时调用 初始化函数(android需要初始化,ios不用)
setupWebViewJavascriptBridge(function (bridge) {
	if (isAndroid) {
		//初始化
		bridge.init(function (message, responseCallback) {
			var data = {
				'Javascript Responds': 'Wee!'
			};
			responseCallback(data);
		})
	}
})

// setupWebViewJavascriptBridge(function (bridge) {
// 	bridge.registerHandler('testJavascriptHandler', function (data, responseCallback) {
// 		var responseData = {
// 			'Javascript Says': 'Right back atcha!'
// 		}
// 		responseCallback(responseData)
// 	})

// 	bridge.callHandler('ObjC Echo', { 'key': 'value' }, function responseCallback(responseData) {
// 		console.log("JS received response:", responseData)
// 	})
// })


export default {
	callHandler(name, data, callback) {
		setupWebViewJavascriptBridge(function (bridge) {
			bridge.callHandler(name, data, callback)
		})
	},
	registerHandler(name, callback) {
		setupWebViewJavascriptBridge(function (bridge) {
			bridge.registerHandler(name, function (data, responseCallback) {
				callback(data, responseCallback)
			})
		})
	}
}

// js 调用 native
// triggerToLoginWithWxAccess // 调用该方法唤起微信授权 
// triggerToGetLocation // 获取定位 { "latitude": "", longitude: "" }
// triggerToCallWxPayment // 调用微信支付 { "prepay_id": "" }

// native 调用 js
// triggerToLoginByWxAccess // native => webview 微信授权后调用该方法 { "accessToken": "" }


// this.$bridge.callHandler('dataToAndroid',msg,(res)=>{
// 	doSomething...
// })